<template>
  <div class="container">
    <div class="app-container">
      <el-tree
        :data="depts"
        :props="props"
        :expand-on-click-node="false"
        icon-class="el-icon-office-building"
        default-expand-all
      >
        <template #default="{data}">
          <el-row style="width: 100%" type="flex" justify="between" align="middle">
            <el-col>{{ data.name }}</el-col>
            <el-col align="center">{{ data.type }}</el-col>
            <el-col align="center">{{ data.managerName }}</el-col>
            <el-col align="center">{{ data.member || 0 }}人</el-col>
            <el-col align="center">
              <el-button type="text" @click="editChild(data.id)">编辑</el-button>
              <el-button type="text" style="margin: 0 10px" @click="del(data.id)">删除</el-button>
              <el-button type="text" @click="addChild(data.id)">新增子项</el-button>
            </el-col>
          </el-row>
        </template>
      </el-tree>
    </div>
    <!-- 新增和编辑部门弹窗 -->
    <addDepts
      ref="refDept"
      :dialog-visible="dialogVisible"
      :current-node-pid="currentNodePid"
      @close="close"
      @addDepartmentSuccess="addDepartmentSuccess"
      @delDepartmentSuccess="delDepartmentSuccess"
    />
  </div>
</template>
<script>
import { getDepartmentList } from '@/api/department'
import { findChildren } from '@/utils/index'
import addDepts from './components/add-depts.vue'
export default {
  components: {
    addDepts
  },
  data() {
    return {
      // 组织架构列表数据
      depts: [],
      // 读取数据的字段名
      props: {
        label: 'name'
      },
      dialogVisible: false,
      currentNodePid: 0
    }
  },
  created() {
    // 获取组织架构列表数据
    this.getDepartments()
  },
  methods: {
    // 获取组织架构列表数据
    async getDepartments() {
      // 调用组织架构列表接口
      const res = await getDepartmentList()
      console.log(res)
      this.depts = findChildren(res.data, 0)
    },
    // 新增子部门
    addChild(pid) {
      // 第一步：弹出对话框
      this.dialogVisible = true
      // 记录新增部门的pid
      this.currentNodePid = pid
    },
    // 关闭弹窗
    close() {
      this.dialogVisible = false
    },
    // 由子组件添加成功后通知父组件刷新列表
    addDepartmentSuccess() {
      this.getDepartments()
    },
    // 编辑部门
    editChild(id) {
      this.dialogVisible = true
      // 因为父组件调用子组件的方法 而且子组件中的方法是请求后端的接口
      // 请求接口是异步执行，所以得添加 $nextTick(() => {}) 方法
      this.$nextTick(() => {
        this.$refs.refDept.getDeptDetail(id)
      })
    },
    // 删除部门
    del(id) {
      // 因为知道form表单在自组件中，数据由子组件提供，则父组件通知自组件删除数据
      this.$nextTick(() => {
        this.$refs.refDept.delDepartment(id)
      })
    },
    // 删除成功通知父组件重新刷新列表
    delDepartmentSuccess() {
      this.getDepartments()
    }
  }
}
</script>
